package com.kk.utils;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.InputStream;
import java.util.List;

/**
 * @author MH
 */

public class XmlUtils {

    public static List<?> parse(Resource resource) {
        try (InputStream inputStream = resource.getInputStream()) {

            //流转 Document 文件
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(inputStream);

            //获取根节点
            Element rootElement = document.getRootElement();
            //获取根节点属性值
            String name = rootElement.attributeValue("name");

            //获取二级子节点
            List<Element> secondElement = rootElement.elements();
            //获取二级子节点属性
            for (Element element : secondElement) {
                element.attributeValue("id");
                element.attributeValue("name");

                //获取三级子节点
                Element thirdElement = element.element("methods");

                //获取四级子节点
                Element fourthElement = thirdElement.element("method");
                //获取四级子节点属性值
                fourthElement.attributeValue("mapping");
                fourthElement.attributeValue("hasArgs");
                fourthElement.attributeValue("hasReturn");
                fourthElement.attributeValue("exception");
            }
            return secondElement;

        } catch (Exception e) {
            throw new UnsupportedOperationException(e.getMessage(), e);
        }
    }


    public static void main(String[] args) {
        String userDir = System.getProperty("user.dir");
        String fileName = "case.xml";
        String path = userDir + File.separator + "utils/src/main/resource" + File.separator + fileName;

        Resource resource = new FileSystemResource(path);
        XmlUtils.parse(resource);
    }
}
